<template>
  <page-meta :page-style="$theme.pageStyle">
    <!-- #ifndef H5 -->
    <navigation-bar
        :front-color="$theme.navColor"
        :background-color="$theme.navBgColor"
    />
    <!-- #endif -->
  </page-meta>
  <view class="index" :style="{backgroundImage: `url(${$domain}/static/icons/matchmaker/posterBg.png)`}">

    <!--顶部-->
    <u-navbar
        :safeAreaInsetTop="false"
        :placeholder="false"
        :is-back="true"
        :is-fixed="true"
        :backIconColor="'#fff'"
        :title="'专属海报'"
        :border-bottom="false"
        :title-bold="true"
        :title-color="'#ffffff'"
        :background="{ background : navBg }"
    >
    </u-navbar>

    <view class="page-poster" v-if="disInfo">
      <image class="poster-bg" mode="aspectFit" :src="`${$domain}/static/icons/matchmaker/posterBox.png`"></image>
      <view class="poster-con">
        <image v-if="!disInfo.avatar" class="con-avatar" mode="aspectFit"
               src="/static/images/user/default_avatar.png"></image>
        <image @click="previewImage" v-else class="con-avatar" mode="aspectFit" :src="disInfo.avatar"></image>
        <view class="con-name">
          {{ disInfo.name }}
        </view>
        <view class="con-ewm">
          <canvas style="position: absolute;top: 0;left: 0;opacity: 0;width: 360rpx;height: 360rpx" type="2d" canvas-id="ewmCanvas"  id="ewmCanvas"></canvas>
          <tki-qrcode
              @click="previewImage"
              v-if="disInfo.id"
              class="ewm-pic"
              ref="qrcode"
              cid="ewmCanvas"
              :val="disInfo.yq_ewm"
              :loadMake="true"
              :size="360"
              @result="qrR" />
<!--          <image class="ewm-pic" mode="aspectFit" src="http://www.jiushuitv.com/content/images/qrcode.jpg"></image>-->
        </view>
        <view class="con-text">
          长按识别二维码开始脱单
        </view>
        <image class="con-logoText" mode="aspectFit" :src="`${$domain}/static/icons/matchmaker/posterText.svg`"></image>
      </view>
    </view>

    <canvas type="2d" v-if="false" id="firstCanvas1" style="width: 100%; height: 100vh;" canvas-id="firstCanvas1"></canvas>

    <view class="page-bottom" v-if="false">
      <view class="bottom-btn" @click="goPoster">
        保存海报
      </view>
    </view>
    <view class="page-bottomFooter"></view>
  </view>
</template>

<script setup lang="ts">
import {computed, reactive, ref, getCurrentInstance} from 'vue'
import {onLoad, onPageScroll, onShow} from "@dcloudio/uni-app";
import {getDisInfoApi, getUserInfoApi} from "@/api/new";
import {useAppStore} from "@/stores/app";

const instance = getCurrentInstance();

const navBg = ref<string>('rgba(255,255,255,0)')

onPageScroll((event: any) => {
  navBg.value = event.scrollTop > 10 ? '#fff' : 'rgba(255,255,255,0)'
})

const navChange = (item: any) => {
  console.log('item', item)
}

const navTo = (url: any) => {
  uni.navigateTo({url})
}

const qrR = (res:any) => {
  console.log('生成的二维码图片',res)
}


let theUserInfo = ref()
const disInfo = ref()

const isShowMain = ref(false)
const getTheUserInfo = async () => {
  theUserInfo.value = await getUserInfoApi({})
  if (theUserInfo.value.is_dis == 0) {
    uni.redirectTo({
      url: '/packagesA/pages/matchmakerAdd/matchmakerAdd'
    })
  } else {
    getDisInfo()
  }
}
const getDisInfo = async () => {
  disInfo.value = await getDisInfoApi({})
  isShowMain.value = true
}

onLoad(() => {
  getTheUserInfo()
})


//长按识别二维码
const previewImage = (e: any) => {
  uni.previewImage({
    // 需要预览的图片链接列表。若无需预览，可以注释urls
    urls: [e.target.src],
    // 为当前显示图片的链接/索引值
    current: e.target.src,
    // 图片指示器样式
    indicator: 'default',
    // 是否可循环预览
    loop: false,
    // 长按图片显示操作菜单，如不填默认为保存相册
    // longPressActions: {
    //   // itemList: [this.l('发送给朋友'), this.l]
    // },
    success: res => {
      console.log('previewImage res', res);
    },
    fail: err => {
      console.log('previewImage err', err);
    }
  });
}

const textCanvas1 = ref(null)

const urlToBase64 = (url: any) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url,
      method: 'GET',
      responseType: 'arraybuffer',
      fail: error => {
        reject(error);
      },
      success: async res => {
        let base64 = uni.arrayBufferToBase64(res.data);
        base64 = 'data:image/jpeg;base64,' + base64;
        resolve(base64);
      }
    })
  })
}

const appStore = useAppStore()
const domain = appStore.getDomain

// 绘制canvas
const drawCanvas = () => {
  uni.createSelectorQuery()
      .in(instance)
      .select('#firstCanvas1')
      .fields({size: true},(res:any) =>{})
      .exec(async (res: any) => {
        console.log('res',res)
        const firstCanvasW = res[0].width
        const firstCanvasH = res[0].height
        console.log('res[0].width',res[0].width)
        let ctx = uni.createCanvasContext('firstCanvas1')
        const bg: any = await urlToBase64(domain + '/static/icons/matchmaker/posterBg.png')
        ctx.drawImage(bg,0, 0, firstCanvasW, firstCanvasH)
        ctx.draw()
      })


  return;
  // 指定this的指向
  // let that = proxy;
  // uni-app 中，不管是小程序，app，h5 在获取元素实例时，都是统一的方法,只要获取元素的宽高
  uni.createSelectorQuery().in(instance).select('#firstCanvas1').fields({node: true, size: true})
      .exec((res) => {
        console.log('res[0]', res)
        // #ifdef MP-WEIXIN
        // 获取设备设备像素比
        const dpr = uni.getSystemInfoSync().pixelRatio;
        // 微信小程序绘制
        let textCanvas = textCanvas1.value = res[0].node;			// 获取元素实例
        textCanvas.width = res[0].width * dpr;					// 设置canvas像素宽
        textCanvas.height = res[0].height * dpr;				// 设置canvas像素高
        let textCtx = textCanvas.getContext('2d');				// 创建二维绘图
        textCtx.clearRect(0, 0, res[0].width, res[0].height);	// 设置画布大小
        textCtx.beginPath();									// 创建一条新的路劲
        textCtx.scale(dpr, dpr);								// 设置x,y缩放(这里作用不大，，没效果)

        // 这里开始绘制canvas内容，绘制的过程当中，不知道是小程序的问题，还是什么问题在绘制有背景图片的内容时，
        // 文字内容必须要延迟绘制，也就是要定时器延迟一定时间才能绘制，要不然就会将文字覆盖在图片下方。
        // 图片的绘制
        const tx = textCanvas.createImage();
        tx.src = "../../..";									// 线上地址或者本地地址都可以
        tx.onload = () => {
          textCtx.drawImage(tx, 20, 20, 100, 100);			// 参数从左到右说明， 图片文件，x轴开始位置，y轴开始位置，x轴结束位置，y轴结束位置
        };
        // 文字设置
        textCtx.fillStyle = "#3085FC";							// 文字颜色
        textCtx.font = "14px sans-serif";						// 字体样式 设置加粗("normal bold 16px sans-serif");
        textCtx.fillText("内容", 160, 45);				        // 设置文字内容， x轴位置，y轴位置

        // 设置分割线
        textCtx.moveTo(10, 130);								// 设置线条开始位置x，y
        textCtx.lineTo(res[0].width - 10, 130);					// 设置线条结束位置x，y
        textCtx.lineWidth = 1;									// 设置线条粗细
        textCtx.strokeStyle = "#e7e7e7";						// 设置线条颜色
        textCtx.stroke();										// 重点，不写线条不显示
        // ... // 其他设置自己查文档很简单
        // #endif
        // #ifdef APP-PLUS || H5
        // app 和 h5 的设置方式是一样的
        let tcx = uni.createCanvasContext('firstCanvas1');			// 通过canvasId 创建画布
        // 设置图片，如果是背景图，就通过获取的实例，获取到他的宽高直接使用
        tcx.drawImage('../../../static/imgage/abc.png', 0, 0, res[0].width, res[0].height);
        // 文字和分割线设置和小程序无异
        tcx.draw();												// 将设置的内容绘制出来，不写不显示
        // #endif
      })
}

// 保存图片
const goPoster = () => {
  drawCanvas()
  return;
  // #ifdef H5
  uni.canvasToTempFilePath({
    canvasId: 'firstCanvas1',
    success: (res) => {
      //把base64转换成Blob数据
      uni.downloadFile({
        url: res.tempFilePath,
        success: (res) => {
          // console.log(res);
          //创建一个a标签
          var link = document.createElement('a');
          //把a标签的href属性赋值到生成好了的url
          link.href = res.tempFilePath;

          //通过a标签的download属性修改下载图片的名字
          link.download = '分享海报.png';
          //让a标签的click函数，直接下载图片
          link.click();
        }
      })
    },

    fail: function (err) {

    }
  })
  // #endif
  // #ifdef MP || APP-PLUS
  uni.canvasToTempFilePath({
    canvasId: 'firstCanvas1',
    success: (res) => {
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success() {
          uni.showModal({
            title: "保存成功",
            content: "图片已成功保存到相册，快去分享到您的圈子吧",
            showCancel: false
          })
        }
      })

    },
    fail: function (err) {

    }
  })
  // #endif

}


</script>

<style lang="scss" scoped>
.index {
  padding-bottom: 60rpx;
  position: relative;
  background-repeat: no-repeat;
  background-size: 100% auto;
  overflow: scroll;
  width: 100%;
  transition: all 1s;
  min-height: calc(100vh - env(safe-area-inset-bottom));
  height: 100vh;
}

.page-poster {
  width: calc(100% - 60rpx);
  margin: 0 auto;
  position: relative;

  .poster-bg {
    position: absolute;
    left: 0;
    top: calc(115rpx - 30rpx);
    width: 100%;
    height: 100%;
    z-index: 0;
  }

  .poster-con {
    text-align: center;
    position: relative;
    z-index: 1;
    padding: 30rpx 30rpx;

    .con-avatar {
      width: 230rpx;
      height: 230rpx;
      border-radius: 50%;
      margin: 0 auto;
      border: 4rpx solid #ffffff;
    }

    .con-name {
      font-size: 28rpx;
      color: #111111;
      text-align: center;
    }

    .con-ewm {
      display: inline-block;
      padding: 20rpx;
      background-color: #ffffff;
      border-radius: 20rpx;
      margin-top: 20rpx;
      position: relative;
      z-index: 2;

      .ewm-pic {
        width: 360rpx;
        height: 360rpx;
      }
    }

    .con-text {
      font-size: 24rpx;
      color: var(--color-minor);
      margin-top: 30rpx;
    }

    .con-logoText {
      display: inline-block;
      width: 376rpx;
      height: 50rpx;
      margin-top: 60rpx;
    }
  }
}

.page-bottom {
  width: 100%;
  padding: 30rpx 30rpx calc(30rpx + env(safe-area-inset-bottom));
  position: fixed;
  bottom: 0;
  z-index: 2;

  .bottom-btn {
    width: 100%;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: rgba(255, 255, 255, .3);
    color: #ffffff;
    font-size: 30rpx;
    font-weight: bold;
    border-radius: 40rpx;
  }

  &Footer {
    height: calc(140rpx + env(safe-area-inset-bottom));
  }
}
</style>
